<template>
  <el-drawer
    :model-value="props.isOpen"
    :title="drawerTitle"
    :size="drawerSize"
    :show-close="true"
    :destroy-on-close="true"
    :before-close="handleClose"
    @update:model-value="handleOpenChange"
  >
    <div class="channel-members-drawer">
      <el-form
        ref="formRef"
        :inline="true"
        :model="form"
        class="search-form bg-bg_color w-full pl-4 pt-[12px] overflow-auto mb-4"
      >
        <el-form-item label="用户名称：" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入用户名称"
            clearable
            class="w-[180px]!"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :icon="useRenderIcon('ri/search-line')"
            :loading="loading"
            @click="onSearch"
          >
            搜索
          </el-button>
          <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <PureTableBar title="" :columns="columns" @refresh="onSearch">
        <template #buttons>
          <el-button
            type="primary"
            :icon="useRenderIcon(AddFill)"
            @click="openDialog('创建')"
          >
            添加名单
          </el-button>
        </template>
        <template v-slot="{ size, dynamicColumns }">
          <div
            v-if="selectedNum > 0"
            v-motion-fade
            class="bg-[var(--el-fill-color-light)] w-full h-[46px] mb-2 pl-4 flex items-center"
          >
            <div class="flex-auto">
              <span
                style="font-size: var(--el-font-size-base)"
                class="text-[rgba(42,46,54,0.5)] dark:text-[rgba(220,220,242,0.5)]"
              >
                已选 {{ selectedNum }} 项
              </span>
              <el-button type="primary" text @click="onSelectionCancel">
                取消选择
              </el-button>
            </div>
            <el-popconfirm title="是否确认删除?" @confirm="onbatchDel">
              <template #reference>
                <el-button type="danger" text class="mr-1!">
                  批量删除
                </el-button>
              </template>
            </el-popconfirm>
          </div>

          <pure-table
            ref="tableRef"
            row-key="Id"
            adaptive
            :adaptiveConfig="{ offsetBottom: 108 }"
            align-whole="center"
            table-layout="auto"
            :loading="loading"
            :size="size"
            :data="dataList"
            :columns="dynamicColumns"
            :pagination="{ ...pagination, size }"
            :header-cell-style="{
              background: 'var(--el-fill-color-light)',
              color: 'var(--el-text-color-primary)'
            }"
            style="height: calc(100vh - 400px)"
            @selection-change="handleSelectionChange"
            @page-size-change="handleSizeChange"
            @page-current-change="handleCurrentChange"
          >
            <template #operation="{ row }">
              <el-popconfirm
                :title="`是否确认删除ID为${row.Id}的频道成员`"
                @confirm="handleDelete(row)"
              >
                <template #reference>
                  <el-button
                    class="reset-margin"
                    link
                    type="danger"
                    :size="size"
                    :icon="useRenderIcon(Delete)"
                  >
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </pure-table>
        </template>
      </PureTableBar>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { PureTable } from "@pureadmin/table";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Delete from "~icons/ep/delete";
import Refresh from "~icons/ep/refresh";
import AddFill from "~icons/ri/add-circle-line";
import { useChannelMembersTable } from "../componentsUtils/useChannelMembersTable";

// 定义props
const props = defineProps<{
  isOpen: boolean;
  channelId?: number;
  lesseeId: number;
  dealerId: number;
}>();

// 定义emits
const emit = defineEmits<{
  "update:isOpen": [value: boolean];
  close: [];
}>();

const tableRef = ref();
const formRef = ref();
const drawerSize = ref("50%");
const drawerTitle = ref("频道黑白名单");

// 监听channelId变化，更新抽屉标题
watch(
  () => props.channelId,
  newChannelId => {
    if (newChannelId) {
      drawerTitle.value = `频道黑白名单`;
    } else {
      drawerTitle.value = "频道黑白名单";
    }
  },
  { immediate: true }
);

// 监听isOpen变化，控制抽屉显示
watch(
  () => props.isOpen,
  newValue => {
    if (newValue) {
      // 当抽屉打开时，自动加载数据
      setTimeout(() => {
        if (props.channelId) {
          // 直接使用已有的form对象，不再重新调用useChannelMembersTable
          form.channelId = props.channelId.toString();
          onSearch();
        } else {
          onSearch();
        }
      }, 100);
    }
  }
);

// 使用频道成员表格的composable
const {
  form,
  loading,
  columns,
  dataList,
  selectedNum,
  pagination,
  deviceDetection,
  onSearch,
  resetForm,
  onbatchDel,
  openDialog,
  handleDelete,
  handleSizeChange,
  onSelectionCancel,
  handleCurrentChange,
  handleSelectionChange
} = useChannelMembersTable(tableRef, props.lesseeId, props.dealerId);

// 处理抽屉状态变化
function handleOpenChange(value: boolean) {
  emit("update:isOpen", value);
}

// 处理抽屉关闭
function handleClose() {
  emit("update:isOpen", false);
  emit("close");
}

onMounted(() => {
  if (props.channelId) {
    form.channelId = props.channelId.toString();
    setTimeout(() => {
      onSearch();
    }, 100);
  }
});
</script>

<style scoped>
.channel-members-drawer {
  height: 100%;
  overflow-y: auto;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}

/* 调整操作列按钮样式 */
:deep(.el-table__cell) {
  .flex.space-x-2 {
    display: flex;
    gap: 8px;
  }
}
</style>
